package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    //类似于盐值 用于加密
    /*@Value("${token.secret}")
    private static String secret;*/

    private static SecretKey secretKey = Keys.hmacShaKeyFor("9uv5Zq2dzTLwRzc2mcwJAw6brgjPm7fu".getBytes());
    //过期时间 毫秒
//    @Value("${token.expire}")
    private static long expireTime = 3600000L;

    public static String createToken(Long userId, String username) {
        //类似于盐值 用于加密
        String token = Jwts.builder()
                //主题
                .setSubject("user_login")
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                //自定义负载
                .claim("userId", userId)
                .claim("username", username)
                //签名
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();
        return token;
    }

    public static Claims parseToken(String token) {
        if (token == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            Claims claims = jwtParser.parseClaimsJws(token).getBody();
            return claims;
            //ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException
        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    public static void main(String[] args) {
        System.out.println(expireTime);
        String token = new JwtUtil().createToken(1L, "admin");

        System.out.println(token);
    }

}
